import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, FormControl } from '@angular/forms';
import { CommonService } from 'src/app/service/common/common.service';
import { MessageService } from 'src/app/service/message.service';

@Component({
  selector: 'app-v-code',
  templateUrl: './v-code.component.html',
  styleUrls: ['./v-code.component.scss']
})
export class VCodeComponent implements OnInit {

  constructor(
    private commonService: CommonService,
    private message: MessageService
  ) { }

  @Input() phone: AbstractControl | string | null = null
  @Input() height: string = 'auto'
  @Input() width: string = '100'
  ngOnInit(): void {
  }

  vCodeText = '获取验证码'
  vCodeBtnLoading = false
  vCodeBtnDisabled = false
  getVerifyCode(){
    console.log(this.phone)
    if(typeof this.phone === 'string'){
      if(!this.phone){
        this.message.error('手机号不能为空')
        return
      }
    }else if(this.phone?.invalid){
      this.phone.markAsTouched()
      this.phone.updateValueAndValidity()
      return
    }
    const param = typeof this.phone === 'string' ? this.phone : this.phone?.value
    this.vCodeBtnLoading = true
    this.vCodeBtnDisabled = true
    this.commonService._getVerifyCode(param).subscribe(res => {
      // if(res.verificationCode && res.verificationCode.indexOf('手机端查收') === -1){
      //   this.message.infoModal('验证码获取成功:' + res.verificationCode)
      // }
      this.vCodeBtnLoading = false
      this.vCodeLoading()
    }, error => {
      if(error && error.error && error.error.Message){
        this.message.error(error.error.Message)
      }else{
        this.message.error('验证码发送失败，请稍后重试')
      }
      
      this.vCodeBtnLoading = false
      this.vCodeBtnDisabled = false
    })
  }
  vCodeTime = 60
  vCodeLoading(){
    this.vCodeText = `${this.vCodeTime}s 后获取`
    setInterval(() => {
      if(this.vCodeTime > 0){
        this.vCodeTime = this.vCodeTime - 1
        this.vCodeText = `${this.vCodeTime}s 后获取`
        return
      }
      this.vCodeText = '获取验证码'
      this.vCodeBtnDisabled = false
    }, 1000)
  }

}
